/*
 * @Author: wwssaabb
 * @Date: 2021-07-08 09:58:31
 * @LastEditTime: 2021-07-14 17:53:40
 * @FilePath: \demo\blog_demo\route\blog.js
 */

//博客展示路由
const router=require('koa-router')()
const Article=require('../model/article')
const Comment=require('../model/comment')
const pagination=require('mongoose-sex-page')
var {getUser}=require('./user')

//当前路由加前缀
router.prefix('/blog')

router.get('/',async (ctx,next)=>{
  const _user=getUser()

  let {page,size,display}=ctx.request.query
  page=parseInt(page?page:1)
  size=parseInt(size?size:4)
  display=parseInt(display?display:5)
  let res=await pagination(Article).page(page).size(size).display(display).find().populate('author').exec() //lean选项的作用是返回的是一个js普通对象

  ctx.render('blog/default',{userInfo:_user,res})
})

router.get('/article',async (ctx,next)=>{
  const _user=getUser()
  const {_id}=ctx.request.query 
  let date=new Date()
  let article=await Article.findOne({_id},{__v:0}).populate('author').exec()
  let comments=await Comment.find({aid:_id},{__v:0}).populate('uid').exec()

  ctx.render('blog/article',{userInfo:_user,article,date,comments})
})

//post

//提交评论
router.post('/comment',async (ctx,next)=>{
  const {aid,uid,content}=ctx.request.body 
  const time=new Date()
  await Comment.create({aid,uid,time,content})
  
  ctx.redirect('/blog/article?_id='+aid)
})


module.exports=router